package cn.group.realm;

import cn.group.mapper.LoginMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import pojo.entity.Manager;
import pojo.entity.User;

import java.util.List;

/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    LoginMapper loginMapper;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权！");
        //声明授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前用户对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        //添加权限   (连接数据库读取)
        info.addStringPermission("user:add");

        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证！");
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
        Manager user = loginMapper.findUserByName(usernamePasswordToken.getUsername());
        if (user==null){
            return null;//抛出用户名不存在异常
        }

        //登陆成功获取当前登陆成功后session
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        //底层会调用凭证匹配器
        //密码认证：由框架完成(1.当前用户资源   2.用户密码认证   3.盐   4.当前realm的名称)
        return new SimpleAuthenticationInfo(user,user.getPassword(), null,getName());
    }
}
